package com.kds.smarthome.service;

import com.kds.smarthome.controller.vo.OutdoorEnvironment;
import com.kds.smarthome.entity.WeatherData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WeatherService {

    @Autowired
    private MongoTemplate mongoTemplate;

//    @Autowired
//    private BuildingService buildingService;  // 假设有一个建筑服务用于获取区域信息

    public OutdoorEnvironment getRecentWeather(String locationCode) {
        // 计算一小时前的时间
        Date oneHourAgo = new Date(System.currentTimeMillis() - 3600 * 1000);

        // 构建查询条件
        Query query = new Query(Criteria.where("region").is(locationCode)
                .and("ts").gte(oneHourAgo))
                .limit(1)  // 只取最新的一条
                .with(Sort.by(Sort.Direction.DESC, "ts"));  // 按时间倒序

        // 查询MongoDB
        WeatherData weatherData = mongoTemplate.findOne(query, WeatherData.class, "data");

        if (weatherData == null) {
            return null;
        }

        // 获取区域名称
        //String regionName = "上海市-宝山区"; //buildingService.getRegionName(locationCode);

        // 转换为前端需要的格式
        OutdoorEnvironment response = new OutdoorEnvironment();
       // response.setRegion(regionName);
        response.setDate(new Date());
        response.setTemperature(Integer.parseInt(weatherData.getTemperature()));
        response.setHumidity(weatherData.getHumidity());
        response.setWeatherText(weatherData.getWeatherText());
        response.setWeatherIcon(Integer.parseInt(weatherData.getWeatherIcon()));
        response.setWindSpeedLevel(weatherData.getWindSpeedLevel() + "级");
        response.setWindDirection(weatherData.getWindDirection());
        response.setWindSpeedKmh(Integer.parseInt(weatherData.getWindSpeedKmh()));
        response.setPm2p5(Integer.parseInt(weatherData.getPm2p5()));
        response.setAirQualityIndex(Integer.parseInt(weatherData.getAirQualityIndex()));
        response.setAirQuality(weatherData.getAirQuality());

        return response;
    }

    public List<Map<String, Object>> getHistoryWeather(String locationCode, Date start, Date end) {
        // 构建查询条件
        Query query = new Query(Criteria.where("region").is(locationCode)
                .and("ts").gte(start).lte(end));

        // 只查询需要的字段
        query.fields()
            .include("ts")
            .include("temperature")
            .include("humidity");

        // 按时间排序
        query.with(Sort.by(Sort.Direction.ASC, "ts"));

        // 查询MongoDB
        List<WeatherData> weatherDataList = mongoTemplate.find(query, WeatherData.class, "data");

        // 转换为前端需要的格式
        return weatherDataList.stream()
            .map(data -> {
                Map<String, Object> item = new HashMap<>();
                item.put("date", data.getTimestamp());
                item.put("temperature", Integer.parseInt(data.getTemperature()));
                item.put("humidity", data.getHumidity());
                return item;
            })
            .collect(Collectors.toList());
    }

}
